<?php

namespace app\helps;
use think\Db;
use think\Exception;

class UserHelper{

    /**
     * 禁用用户
     * @param $user
     * @param  $isOpen 启用
     * @param $cause
     */
    public function userStatus($user,$isOpen,$cause) {
        Db::startTrans();
        try{
            $updateUser=[];
            $updateUser["status"]=$isOpen?1:0;
            if (!$isOpen){
                $updateUser["activity"]=0;
            }
            $updateUserRes =Db::table("tb_user")->where("id",$user["id"])->update($updateUser);
            if (!$updateUserRes){
                Db::rollback();
                return "更新用户状态失败";
            }
            $updateRecord = $this->updateUserStatusRecord($user,$cause);
            if (!$updateRecord){
                Db::rollback();
                return "更新用户状态记录失败";
            }
            Db::commit();
            return 1;
        }catch (Exception $exception){
            Db::rollback();
            return "异常:".$exception->getMessage();
        }
        return true;
    }


    /**
     *
     * 如果用户被禁用的 则不能激活
     * 用户激活 给商城用
     * @param $user 用户对象
     * @param $cause 激活原因 字符串
     * 返回1 标识成功 ;否则返回错误信息
     *
     */
    public function userActivity($user,$cause,$openActity=true) {
        if ($openActity&&$user['status']==0 ){
            return "用户禁用了,不能激活";
        }
        Db::startTrans();
        try{
            $updateUser=[];
            $updateUser["activity"]=$openActity?1:0;
            if ($openActity){
                $updateUser["activity_time"]=date('Y-m-d H:i:s');
            }
            if ($updateUser["activity"] != $user["activity"]){
                $updateUserRes =Db::table("tb_user")->where("id",$user["id"])->update($updateUser);
                if (!$updateUserRes){
                    Db::rollback();
                    return "失败：更新激活状态失败";
                }
            }
           $updateRecord = $this->updateUserStatusRecord($user,$cause);
           if (!$updateRecord){
               Db::rollback();
               return "失败：更新激活记录失败";
           }
            Db::commit();
            return 1;
        }catch (Exception $exception){
            Db::rollback();
            return "失败：" .$exception->getMessage();
        }

    }

    private function updateUserStatusRecord($user,$mark){
        $data =[];
        $data["uid"]=$user["id"];
        $data["user_name"]=$user["username"];
        $data["mark"]=$mark;
        $data["time"]=date('Y-m-d H:i:s');
        return  Db::table("tb_user_status_record")->insert($data);
    }






}